<template>
  <div class="login-container">
    <div class="login-box">
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="loginForm.username"
            :class="{ 'error': errors.username }"
            placeholder="请输入用户名"
          >
          <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="loginForm.password"
            :class="{ 'error': errors.password }"
            placeholder="请输入密码"
          >
          <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
        </div>

        <div class="error-alert" v-if="errors.login">
          {{ errors.login }}
        </div>

        <div class="form-group checkbox">
          <label>
            <input type="checkbox" v-model="loginForm.remember">
            记住我
          </label>
        </div>

        <button type="submit" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <div class="footer">
        <router-link to="/register">还没有账号？立即注册</router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/auth'
import { setSaToken, setUserInfo, setRememberedUsername, getRememberedUsername, setCurrentUserName } from '@/utils/auth'

export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false
      },
      errors: {},
      loading: false
    }
  },
  created() {
    // 如果有记住的用户名，自动填充
    const rememberedUsername = getRememberedUsername()
    if (rememberedUsername) {
      this.loginForm.username = rememberedUsername
      this.loginForm.remember = true
    }
  },
  methods: {
    validateForm() {
      this.errors = {}
      let isValid = true

      if (!this.loginForm.username) {
        this.errors.username = '请输入用户名'
        isValid = false
      }
      
      if (!this.loginForm.password) {
        this.errors.password = '请输入密码'
        isValid = false
      }

      return isValid
    },
    async handleLogin() {
      if (!this.validateForm()) {
        return
      }

      this.loading = true
      
      try {
        const response = await login({
          userName: this.loginForm.username,
          password: this.loginForm.password
        })

        if (response.success) {
          console.log('登录成功，获取到SaToken:', response.data)
          
          // 检查是否有loginId
          if (!response.data.loginId) {
            console.log('警告: 登录响应中没有loginId，将等待后端生成')
            
            // 立即调用状态检查API，尝试获取loginId
            try {
              const { checkLoginStatus } = await import('@/api/auth')
              const statusResponse = await checkLoginStatus()
              
              if (statusResponse.success && statusResponse.data && statusResponse.data.loginId) {
                console.log('立即检查获取到loginId:', statusResponse.data.loginId)
                
                // 更新response.data
                response.data.loginId = statusResponse.data.loginId
              } else {
                console.log('立即检查未获取到loginId，将依赖轮询机制')
              }
            } catch (checkError) {
              console.error('检查登录状态出错:', checkError)
            }
          }
          
          // 存储SaToken信息
          setSaToken(response.data)
          
          // 保存用户名到内存中
          setCurrentUserName(this.loginForm.username)
          console.log('内存中保存了用户名:', this.loginForm.username)
          
          // 如果后端返回了用户信息，保存它
          if (response.data.userInfo) {
            setUserInfo(response.data.userInfo)
          } else {
            // 如果没有用户信息，我们保存基本信息
            setUserInfo({
              userName: this.loginForm.username
            })
          }
          
          // 如果勾选了"记住我"，保存用户名
          if (this.loginForm.remember) {
            setRememberedUsername(this.loginForm.username)
          }
          
          // 触发登录成功事件，通知其他组件（如导航栏）
          this.$root.$emit('login-success', response.data)
          
          // 延迟一下确保事件完全处理
          setTimeout(() => {
            // 登录成功，跳转到首页或者之前访问的页面
            const redirectPath = this.$route.query.redirect || '/'
            
            // 使用window.location.href强制刷新页面，确保状态正确
            window.location.href = redirectPath.startsWith('/') 
              ? window.location.origin + redirectPath 
              : redirectPath
          }, 300)
        } else {
          this.errors.login = response.message || '登录失败，请稍后重试'
        }
      } catch (error) {
        console.error('登录错误:', error)
        this.errors.login = error.message || '登录失败，请稍后重试'
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  color: #4CAF50;
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

input[type="text"],
input[type="password"] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

input[type="text"]:focus,
input[type="password"]:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.checkbox {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.checkbox label {
  display: flex;
  align-items: center;
  margin: 0;
  cursor: pointer;
}

.checkbox input[type="checkbox"] {
  margin-right: 8px;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #3d8b40;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.footer {
  margin-top: 20px;
  text-align: center;
}

.footer a {
  color: #4CAF50;
  text-decoration: none;
}

.footer a:hover {
  text-decoration: underline;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.error-alert {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
  text-align: center;
  border-left: 4px solid #d32f2f;
}

input.error {
  border-color: #ff4d4f;
}

input.error:focus {
  border-color: #ff4d4f;
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
}
</style> 